#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:Venus
@file:n_neighbors_测试.py
@time:2021/12/12/14：03
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection  import cross_val_score
import time
import pylab as mpl

winequality = pd.read_csv(r'C:\Users\Venus\Desktop\Pycharm_Workspace\venv\智能优化方法\大作业\data\winequality-red500-2.csv', ';')
wine_data = winequality.iloc[:, :-1]
wine_target = winequality['quality']

k_range = range(1, 31)
k_error = []

if __name__ == '__main__':
    # 循环，取k=1到k=31，查看误差效果
    for ki in k_range:
        # 划分数据集
        winequality_data_train, winequality_data_test, winequality_taget_train, winequality_taget_test = train_test_split(
            wine_data, wine_target, test_size=0.2, random_state=6)
        # 标准化数据集
        stdScale = StandardScaler().fit(winequality_data_train)
        winequality_trainScaler = stdScale.transform(winequality_data_train)
        winequality_testScaler = stdScale.transform(winequality_data_test)
        # 训练KNN
        clf = KNeighborsClassifier(n_neighbors=ki)
        clf.fit(winequality_trainScaler, winequality_taget_train)
        # --------------fitness-------------------
        prediction = clf.predict(winequality_testScaler)
        # correct_num = 0
        # for k in range(len(winequality_taget_test)):
        #     if prediction[k] == winequality_taget_test.values[k]:
        #         correct_num += 1
        # correct_rate = correct_num / len(winequality_taget_test)
        # fitness.append(correct_rate)

        # cv参数决定数据集划分比例，这里是按照5:1划分训练集和测试集
        scores = cross_val_score(clf, winequality_trainScaler, winequality_taget_train, cv=6, scoring='accuracy')
        k_error.append(1 - scores.mean())

    # 画图，x轴为k值，y值为误差值
    plt.plot(k_range, k_error)
    plt.xlabel('Value of K for KNN')
    plt.ylabel('Error')
    plt.show()
